package com.syqc.videos

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.AppContext
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.ActionData
import com.syqc.entity.RealVideoInfo
import com.syqc.entity.VideoHost
import com.syqc.entity.VideosPass
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import com.syqc.utils.ToolsUtil
import com.syqc.utils.VideoHostUtil
import kotlin.concurrent.thread

class RealPlayerVM : AutoDisposeViewModel() {
    //服务器地址
    private lateinit var videoHost: VideoHost
    var carId: String = ""
        set(value) {
            field = value
            if (value.isNotEmpty()) videoHost = VideoHostUtil.getVideoHost(value)
        }

    //对讲通道
    private var audioPass = ""
    private var audioTcPass = ""
    fun getAudioPass() = audioPass

    //是否28181设备
    var is28181 = false

    //云台控制速度
    var speed = 127

    //控制通道
    var controlPass = ""

    //视频通道信息
    private var videos = ""

    var isShowPopup
        get()= CacheMMKV.decodeBooleanSave("isMenuReal",true)
        set(value){
            CacheMMKV.encodeSave("isMenuReal",value)
        }

    //视频通道信息集合
    private val passInfos = mutableListOf<RealVideoInfo>()
    private val passDesc = AppContext.getDescById(R.string.desc_video_pass)
    private val _passLive = MutableLiveData<MutableList<RealVideoInfo>>()
    val passLive: LiveData<MutableList<RealVideoInfo>> = _passLive

    fun handlePass() {
        handlePass(videos)
    }

    fun handlePass(videos: String?) {
        audioPass = ""
        is28181 = false
        passInfos.clear()
        if (videos.isNullOrEmpty() || videos.length < 4) return
        this.videos = videos
        val entity = GsonUtil.formObject<VideosPass>(videos)
        if (entity.vs != null) {
            val passArray = entity.vs.split(",")
            passArray.forEach {
                val infoArray = it.split(":")
                val passNum = infoArray[0]
                val passName = infoArray[1]
                if (passName.isEmpty()) {
                    passInfos.add(
                        RealVideoInfo(
                            videoPass = passNum,
                            videoName = "$passDesc $passNum"
                        )
                    )
                } else {
                    passInfos.add(RealVideoInfo(videoPass = passNum, videoName = passName))
                }
            }
        }
        is28181 = if (!entity.t.isNullOrEmpty()) {
            entity.t == "28181"
        } else {
            false
        }
        audioTcPass = entity.tc ?: ""
        audioPass = if (audioTcPass.isEmpty()) {
            if (passInfos.isNotEmpty()) passInfos.first().videoPass else ""
        } else audioTcPass

        _passLive.postValue(passInfos)
    }

    /**
     * 设置对讲通道
     *
     * @param pass
     */
    fun setAudioPass(pass: String) {
        if (audioTcPass.isNotEmpty()) return
        audioPass = pass
    }

    //**************************************************************************************************/
    /** drct：1上移 2下移 3左移 4右移 0停止 speed：旋转速度0-255,默认127 */
    private fun getControlUrl(drct: Int): String {
        return "${VideoHostUtil.getHost(videoHost)}/phone.cloud_ctr.0.$carId.$controlPass.$drct.$speed"
    }

    /**
     *1.调整焦距(0焦距变小 1焦距变大) 2.调整光圈(0光圈放大 1光圈缩小) 3.调整雨刷(0雨刷关闭 1雨刷打开)
     *4.调整补光(0补光关闭 1补光打开) 5.调整变倍(0变倍调大 1变倍调小)
     * @param type
     * @param action
     * @return
     */
    private fun getActionUrl(type: Int, action: Int): String {
        return "${VideoHostUtil.getHost(videoHost)}/phone.cloud_ctr.$type.$carId.$controlPass.$action"
    }

    /**
     * 判断参数是否合格
     *
     * @return
     */
    fun isParamsOk(): Boolean {
        if (carId.isEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return true
        }
        if (audioPass.isEmpty()) {
            toast(R.string.hint_toast_choose_channel)
            return true
        }
        return false
    }

    /**
     * 是否已经选车
     *
     * @return
     */
    fun isChooseCar(): Boolean {
        if (carId.isEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return true
        }
        return false
    }

    //云台控制
    fun control(drct: Int) {
        toastLoading(true)
        if (isParamsOk()) return
        ServiceHelper.getRepository().getVideoState(getControlUrl(drct)).autoDispose(this)
            .subscribe({
                if (it == "1") {
                    toastLoading(false)
//                toast(R.string.toast_set_success)
                    return@subscribe
                }
            }, error)
    }

    /**
     * 1.调整焦距(0焦距变小 1焦距变大) 2.调整光圈(0光圈放大 1光圈缩小) 3.调整雨刷(0雨刷关闭 1雨刷打开)
     * 4.调整补光(0补光关闭 1补光打开) 5.调整变倍(0变倍调大 1变倍调小)
     *
     * @param type
     * @param action
     */
    fun changeAction(type: Int, action: Int) {
        toastLoading(true)
        if (isParamsOk()) return
        ServiceHelper.getRepository().getVideoState(getActionUrl(type, action)).autoDispose(this)
            .subscribe({
                if (it == "1") {
                    if (type == 3) setWiper(action)
                    else if (type == 4) setLight(action)
                    toastLoading(false)
//                toast(R.string.toast_set_success)
                    return@subscribe
                }
            }, error)
    }

    private fun setLight(light: Int) {
        val action = getAction()
        putAction(light, action.wiper)
    }

    private fun setWiper(wiper: Int) {
        val action = getAction()
        putAction(action.light, wiper)
    }


    private val actionMap = HashMap<String, ActionData>()

    private fun putAction(light: Int, wiper: Int) {
        val actionData = actionMap[audioPass]
        if (actionData == null) {
            actionMap[audioPass] = ActionData(light, wiper)
        } else {
            actionData.light = light
            actionData.wiper = wiper
        }
        actionLive.postValue(true)
    }

    fun getAction(): ActionData {
        return actionMap[audioPass] ?: ActionData()
    }

    var actionLive = MutableLiveData<Boolean>()

    fun clearMap() {
        actionMap.clear()
    }

    ///////////////////////////////////////
    fun isClient(videos: String?) {
        when (videoHost.isClient) {
            null -> {
                thread {
                    val isClient = ToolsUtil.isReachableByTcp(videoHost.ip, videoHost.port)
                    VideoHostUtil.changeHost(videoHost.index, isClient)
                    if (isClient) {
                        handlePass(videos)
                    } else {
                        toast(VideoHostUtil.getHost(videoHost) + "\n" + AppContext.getDescById(R.string.toast_port_faile))
                        _passLive.postValue(mutableListOf())
                    }
                }
            }

            false -> {
                toast(VideoHostUtil.getHost(videoHost) + "\n" + AppContext.getDescById(R.string.toast_port_faile))
                _passLive.postValue(mutableListOf())
            }

            else -> {
                handlePass(videos)
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        VideoHostUtil.clearHostsClient()
    }


}